package com.ruoze.bdp.utils;

import org.springframework.context.MessageSource;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
import java.util.Optional;


public class MessageConverterUtil {
    private static LocaleResolver localeResolver = new SessionLocaleResolver();
    private static MessageSource messageSource;

    public static String getMessage(String code){
        return messageSource.getMessage(code, null, getCurrentLocale());
    }

    public static String getMessage(String code, Object...message){
        return messageSource.getMessage(code, message, getCurrentLocale());
    }

    private static Locale getCurrentLocale() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(!Optional.ofNullable(requestAttributes).isPresent()){
            return Locale.SIMPLIFIED_CHINESE;
        }

        HttpServletRequest request = requestAttributes.getRequest();
        HttpServletResponse response = requestAttributes.getResponse();
        Locale locale = localeResolver.resolveLocale(request);
        localeResolver.setLocale(request, response,locale);
        Object useInternationalization = request.getAttribute("useInternationalization");
        if(!Optional.ofNullable(useInternationalization).isPresent()){
            return Locale.SIMPLIFIED_CHINESE;
        }
        return (boolean) useInternationalization ? locale : Locale.SIMPLIFIED_CHINESE;
    }
}
